//
//  MainTabBarController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "MainTabBarController.h"

#import "HomeViewController.h"
#import "BusinessTableViewController.h"
#import "ActViewController.h"
#import "ShopCarViewController.h"
#import "MineTableViewController.h"
#import "BaseNavigationController.h"
#import "ChatViewController.h"
#import "ChatListViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "ChatDemoHelper.h"
#import "UITabBar+badge.h"
#import "ReadLoginData.h"
#import "CustomAlertWindow.h"
#import <JDStatusBarNotification.h>

#import "KWeiHomeController.h"

static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface MainTabBarController ()<EMClientDelegate>
{
    MineTableViewController *_mineVC;
    ChatListViewController *_chatListVC;
    //    __weak CallViewController *_callController;
    
    UIBarButtonItem *_addFriendItem;
    NSString *_username;
}

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@property (nonatomic,copy)NSString *judgeViewShowAlertString;

@property (nonatomic,copy)NSString *username;


@end

@implementation MainTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTarBarViews];
    [[EMClient sharedClient] addDelegate:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(judgeShowAlertStirng:) name:KNOTIFICATION_JUDGESHOWALERT object:nil];
}



- (void)setupTarBarViews
{
    
    //tabbar背景色
    UIView *bgView = [[UIView alloc] initWithFrame:self.tabBar.bounds];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.tabBar insertSubview:bgView atIndex:0];
    self.tabBar.opaque = YES;
    //首页
    KWeiHomeController *homeCtrl = [[KWeiHomeController alloc] init];
//    HomeMainController *homeCtrl = [[HomeMainController alloc] init];
    [self addChildViewCtrlWithTitle:@"首页" image:@"tabar_notselected1" selctedImage:@"tabar_selected1" ctrl:homeCtrl];
    
    //商家
    BusinessTableViewController *businessCtrl = [[BusinessTableViewController alloc] init];
    [self addChildViewCtrlWithTitle:@"商家" image:@"tabar_notselected2" selctedImage:@"tabar_selected2" ctrl:businessCtrl];
    
    //购物车
    ShopCarViewController *shopCarCtrl = [[ShopCarViewController alloc] init];
    [self addChildViewCtrlWithTitle:@"购物车" image:@"tabar_notselected3" selctedImage:@"tabar_selected3" ctrl:shopCarCtrl];
    
    //我的
    MineTableViewController *mineCtrl = [[MineTableViewController alloc] init];
    [self addChildViewCtrlWithTitle:@"我的" image:@"tabar_notselected4" selctedImage:@"tabar_selected4" ctrl:mineCtrl];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeIndex) name:@"DidClickButtonChangeTabBarControllerSelected" object:
     nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recordShowOrDissMissAlert:) name:@"JudgeShowOrDissMissAlert" object:nil];
}

- (void)recordShowOrDissMissAlert:(NSNotification *)notuficaString {
    
}

- (void)changeIndex {
    self.selectedViewController = [self.viewControllers objectAtIndex:3];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addChildViewCtrlWithTitle:(NSString *)title image:(NSString *)image selctedImage:(NSString *)selectImage ctrl:(UIViewController *)ctrl{

    ctrl.tabBarItem.image = [UIImage imageNamed:image];
    //如果图片上面包括了icon与文字，要把图片往下移动的话。可以使用下面这句代码
    //    ctrl.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
    //解决图片变蓝的问题
    UIImage *originalImage = [UIImage imageNamed:selectImage];
    ctrl.tabBarItem.selectedImage = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    设置标题
//        ctrl.tabBarItem.title = title;
//        ctrl.navigationItem.title = title;

    ctrl.title = title;
    
    //初始化文字的属性
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[NSForegroundColorAttributeName] = DEFAULT_COLOR;
    
    //设置tabbarItem 标题的文字属性
    [ctrl.tabBarItem setTitleTextAttributes:dic forState:UIControlStateSelected];

    BaseNavigationController *navCtrl = [[BaseNavigationController alloc] initWithRootViewController:ctrl];
    [self addChildViewController:navCtrl];
    
}

-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    NSLog(@"%@",(BaseNavigationController *)[self.viewControllers objectAtIndex:3].childViewControllers);
    if (_mineVC) {
        MineTableViewController *mine = [self.viewControllers objectAtIndex:4].childViewControllers.firstObject;
        if (unreadCount > 0) {
            [mine.tabBarController.tabBar showBadgeOnItemIndex:3];
        }else{
            [mine.tabBarController.tabBar hideBadgeOnItemIndex:3];
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"badgeValue" object:nil];
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:[ChatDemoHelper setUnReadMessageCount]];
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    _connectionState = connectionState;
    [_chatListVC networkChanged:connectionState];
}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
}

- (void)showActiveNotificationWithMessage:(EMMessage *)message {
    EMMessageBody *messageBody = message.body;
    NSString *messageStr = nil;
    switch (messageBody.type) {
        case EMMessageBodyTypeText:
        {
            messageStr = ((EMTextMessageBody *)messageBody).text;
        }
            break;
        case EMMessageBodyTypeImage:
        {
            messageStr = NSLocalizedString(@"图片", @"Image");
        }
            break;
        case EMMessageBodyTypeLocation:
        {
            messageStr = NSLocalizedString(@"位置", @"Location");
        }
            break;
        case EMMessageBodyTypeVoice:
        {
            messageStr = NSLocalizedString(@"音频", @"Voice");
        }
            break;
        case EMMessageBodyTypeVideo:{
            messageStr = NSLocalizedString(@"视频", @"Video");
        }
            break;
        default:
            break;
    }
    
    do {
#warning yonghuming
        [ReadLoginData reloadUserInfoWithUserNumber:message.from andInfoModel:^(SellerUserInfoModel *infoModel) {
            NSString *alertString;
            
            if (infoModel.member_name.length) {
                alertString = [NSString stringWithFormat:@"%@:%@",infoModel.member_name,messageStr];
            } else {
                alertString = [NSString stringWithFormat:@"%@:%@",message.from,messageStr];
            }
            
            if (!self.judgeViewShowAlertString.length) {
                [JDStatusBarNotification addStyleNamed:JDStatusBarStyleDark prepare:^JDStatusBarStyle *(JDStatusBarStyle *style) {
                    style.animationType = JDStatusBarAnimationTypeFade;
                    style.barColor = [UIColor blackColor];
                    style.textColor = [UIColor whiteColor];
                    
                    return style;
                }];
                
                [JDStatusBarNotification showWithStatus:alertString dismissAfter:3.f styleName:JDStatusBarStyleDark];
//                NSLog(@"%@",view);
            
            }
            
        }];
        
    } while (0);
}

- (void)coverWindowClick {
    NSLog(@"%s",__func__);
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
#warning 修改推送消息设置
    self.username = [NSString string];
    
    
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    NSString *alertBody = nil;
    if (options.displayStyle == EMPushDisplayStyleMessageSummary) {
        EMMessageBody *messageBody = message.body;
        NSString *messageStr = nil;
        switch (messageBody.type) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"图片", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"位置", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"音频", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"视频", @"Video");
            }
                break;
            default:
                break;
        }
        
        do {
#warning yonghuming
            //            NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
            NSString *title = @"用户名";
            if (message.chatType == EMChatTypeGroupChat) {
                NSDictionary *ext = message.ext;
                if (ext && ext[kGroupMessageAtList]) {
                    id target = ext[kGroupMessageAtList];
                    if ([target isKindOfClass:[NSString class]]) {
                        if ([kGroupMessageAtAll compare:target options:NSCaseInsensitiveSearch] == NSOrderedSame) {
                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                    else if ([target isKindOfClass:[NSArray class]]) {
                        NSArray *atTargets = (NSArray*)target;
                        if ([atTargets containsObject:[EMClient sharedClient].currentUsername]) {
                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                }
                NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
                for (EMGroup *group in groupArray) {
                    if ([group.groupId isEqualToString:message.conversationId]) {
                        title = [NSString stringWithFormat:@"%@(%@)", message.from, group.subject];
                        break;
                    }
                }
            }  else if (message.chatType == EMChatTypeChatRoom) {
                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[EMClient sharedClient] currentUsername]];
                NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
                NSString *chatroomName = [chatrooms objectForKey:message.conversationId];
                if (chatroomName)
                {
                    title = [NSString stringWithFormat:@"%@(%@)", message.from, chatroomName];
                }
            }
            
            alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
        } while (0);
    } else{
#warning 消息推送
        alertBody = NSLocalizedString(@"您有一则新消息", @"you have a new message");
//        alertBody = [NSString stringWithFormat:@"您有一则来自%@的消息",message.from];
        
        
        EMMessageBody *messageBody = message.body;
        NSString *messageStr = nil;
        switch (messageBody.type) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"图片", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"定位", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"音频", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"视频", @"Video");
            }
                break;
            default:
                break;
        }
        
//        alertBody = [NSString stringWithFormat:@"%@:%@",self.username,messageStr];
        
    }
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    BOOL playSound = NO;
    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
        self.lastPlaySoundDate = [NSDate date];
        playSound = YES;
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
    [userInfo setObject:message.conversationId forKey:kConversationChatter];

    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        if (playSound) {
            content.sound = [UNNotificationSound defaultSound];
        }
        content.body =alertBody;
        content.userInfo = userInfo;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
    } else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = alertBody;
        notification.alertAction = NSLocalizedString(@"打开", @"Open");
        notification.timeZone = [NSTimeZone defaultTimeZone];
        if (playSound) {
            notification.soundName = UILocalNotificationDefaultSoundName;
        }
        notification.userInfo = userInfo;
        
        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}


- (void)judgeShowAlertStirng:(NSNotification *)notification {
    self.judgeViewShowAlertString = notification.object;
}

- (void)connectionStateDidChange:(EMConnectionState)aConnectionState {
    NSLog(@"%u",aConnectionState);
    
    switch (aConnectionState) {
        case EMConnectionConnected:
            NSLog(@"已连接");
            break;
            
        case EMConnectionDisconnected:
            NSLog(@"未连接");
            break;
        default:
            break;
    }
    
}

@end
